#!/bin/bash

if [ -f ./func.sh ]; then
  source ./func.sh
elif [ -f scripts/func.sh ]; then
  source scripts/func.sh
fi

CONFIG_BLOCK=${CHANNEL_ARTIFACTS}/${APP_CHANNEL}_block.pb
CONFIG_JSON=${CHANNEL_ARTIFACTS}/${APP_CHANNEL}.json
ORI_PB=${CHANNEL_ARTIFACTS}/${APP_CHANNEL}.pb
rm -f ${CONFIG_BLOCK} ${CONFIG_JSON} ${ORI_PB}

MODIFIED_JSON=${CHANNEL_ARTIFACTS}/modified_config.json
MODIFIED_PB=${CHANNEL_ARTIFACTS}/modified_config.pb
UPDATE_PB=${CHANNEL_ARTIFACTS}/update.pb
UPDATE_JSON=${CHANNEL_ARTIFACTS}/update.json
rm -f ${MODIFIED_JSON} ${MODIFIED_PB} ${UPDATE_PB} ${UPDATE_JSON}

ENVELOPE_JSON=${CHANNEL_ARTIFACTS}/envelope.json
ENVELOPE_PB=${CHANNEL_ARTIFACTS}/envelope.pb
rm -f ${ENVELOPE_JSON} ${ENVELOPE_PB}

NEW_ORG_DIR=/tmp/org2
NEW_ORG_JSON=${NEW_ORG_DIR}/org2.json



# sleep 3

fetchBlock ${APP_CHANNEL} ${ORDERER0_URL} ${ORDERER0_TLS_ROOTCERT} "config" ${CONFIG_BLOCK}
echo_b "1"


configtxlator proto_decode \
  --input ${CONFIG_BLOCK}\
  --type common.Block | jq .data.data[0].payload.data.config > ${CONFIG_JSON}
echo_b "2"


# jq -s '.[0] * {"channel_group":{"groups":{"Consortiums":{"groups":{"SampleConsortium":{"groups":{"Org2MSP":.[1]}}}}}}}' ${CONFIG_JSON} ${NEW_ORG_JSON} >${MODIFIED_JSON}
jq -s '.[0] * {"channel_group":{"groups":{"Application":{"groups": {"Org2MSP":.[1]}}}}}' ${CONFIG_JSON} ${NEW_ORG_JSON} > ${MODIFIED_JSON}
echo_b "3"


configtxlator proto_encode --input ${CONFIG_JSON} --type common.Config --output ${ORI_PB}
configtxlator proto_encode --input ${MODIFIED_JSON} --type common.Config --output ${MODIFIED_PB}
echo_b "4"

configtxlator compute_update \
  --channel_id ${APP_CHANNEL} \
  --original ${ORI_PB} \
  --updated ${MODIFIED_PB} \
  --output ${UPDATE_PB}
echo_b "6"

configtxlator proto_decode --input ${UPDATE_PB} --type common.ConfigUpdate > ${UPDATE_JSON}
echo_b "7"

echo '{"payload":{"header":{"channel_header":{"channel_id":"'${APP_CHANNEL}'","type":2}},"data":{"config_update":'$(cat ${UPDATE_JSON})'}}}' | jq . > ${ENVELOPE_JSON}
echo_b "8"

configtxlator proto_encode \
  --input ${ENVELOPE_JSON} \
  --type common.Envelope \
  --output ${ENVELOPE_PB}
echo_b "9"

signconfigtx ${APP_CHANNEL} 1 0 ${ENVELOPE_PB}
signconfigtx ${APP_CHANNEL} 1 1 ${ENVELOPE_PB}
echo_b "10"

channelUpdate ${APP_CHANNEL} 1 0 ${ORDERER0_URL} ${ORDERER0_TLS_ROOTCERT} ${ENVELOPE_PB}
echo_b "11"

# new_config_tx=/tmp/channel-artifacts/businesschannel_new.tx
# fetchBlock ${APP_CHANNEL} ${ORDERER0_URL} ${ORDERER0_TLS_ROOTCERT} "0" ${new_config_tx}

